package com.jlect.swebing.ui.client.menu;

import com.google.gwt.core.client.GWT;
import com.jlect.swebing.ui.client.GComponent;
import com.jlect.swebing.ui.client.button.GToggleButton;

/**
 * Provides menu bar components for the base two types of menu items : {@link com.jlect.swebing.ui.client.menu.GMenu}
 * and {@link com.jlect.swebing.ui.client.menu.GMenuItem}
 *
 * @author Sergey Kozmin
 * @since 28.11.2007 11:27:11
 */
public class MenuItemProvider implements MenuBarItemProvider {
    public MenuBarItem createMenuBarItem(GComponent component) {
        MenuBarItem item;
        if(component instanceof GMenu) {
            GMenu menu = (GMenu) component;
            item = new MenuBasedBarItem(menu);
        } else if(component instanceof GMenuItem) {
            GMenuItem menuItem = (GMenuItem) component;
            item = new MenuItemBasedBarItem(menuItem);
        } else {
            throw new IllegalArgumentException("Could not create MenuBarItem for the component of class [" +
                    GWT.getTypeName(component) + "], use custom provider. ");
        }
        return item;
    }

    private static class MenuBasedBarItem implements MenuBarItem {
        private GToggleButton toggleButton;
        private GMenu menu;

        public MenuBasedBarItem(GMenu menu) {
            this.menu = menu;
            toggleButton = new GToggleButton(menu.getText());
        }

        public GComponent getView() {
            return toggleButton;
        }

        public void activate() {
            toggleButton.setSelected(true);
            menu.showPopup(toggleButton.getX(), toggleButton.getY() + toggleButton.getHeight());
        }

        public void deActivate() {
            toggleButton.setSelected(false);
            menu.hidePopup();
        }

        public void performAction() {
            if(toggleButton.isSelected()) {
                deActivate();
            } else {
                activate();
            }
        }
    }

    private static class MenuItemBasedBarItem implements MenuBarItem {
        private GToggleButton toggleButton;
        private GMenuItem item;

        public MenuItemBasedBarItem(GMenuItem item) {
            this.item = item;
            toggleButton = new GToggleButton(item.getText());
        }

        public GComponent getView() {
            return toggleButton;
        }

        public void activate() {
            toggleButton.setSelected(true);
        }

        public void deActivate() {
            toggleButton.setSelected(false);
        }

        public void performAction() {
            item.fireActionPerformed(null);
            deActivate();
        }
    }
}
